package com.xz.simplerpc.rpc.proxy;

import com.xz.simplerpc.extension.URL;
import com.xz.simplerpc.rpc.api.*;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by fingal on 2018/1/7.
 */
public class JdkProxyFactory {

    @SuppressWarnings("unchecked")
    public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, new InvokerInvocationHandler(invoker));
    }

    public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) {
        return new Invoker<T>() {
            @Override
            public Class<T> getInterface() {
                return type;
            }

            @Override
            public Result invoke(Invocation invocation) throws RpcException {
                try {
                    Method method = proxy.getClass().getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                    return new RpcResult(method.invoke(proxy, invocation.getArguments()));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }
}
